/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fait.ferm.persists;

import fait.ferm.global.Glob;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @author Greg
 */
public class Plan_details_care extends PersistsObject {
    public int plan_id;
    public int cow_group_id;
    public int supplies_id;
    public double quantity;
    
    public Plan_details_care() {
        super();
        
        plan_id = -1;
        cow_group_id = -1;
        supplies_id = -1;
        quantity = -1;
        
        table = "plan_details_care";
    }
    
    public Plan_details_care(int pId) throws Exception {
        super(pId);
        table = "plan_details_care";
        load();
    }
    
    @Override
    public void load() throws Exception {
        boolean notSuccessfully=true;
		if(id==-1) {
			throw new Exception("Объект "+table+" отсутствует в базе");
		}	
		try (Statement st = con.createStatement()) {
			String q = "SELECT plan_id, cow_group_id, supplies_id, quantity FROM "+table+" WHERE id = " + id;
			ResultSet rs = st.executeQuery(q);
			if(rs.next()){
				notSuccessfully=false;
				plan_id = rs.getInt("plan_id");
				cow_group_id = rs.getInt("cow_group_id");
                supplies_id = rs.getInt("supplies_id");
                quantity = rs.getDouble("quantity");
			}
			rs.close();
		}
		if(notSuccessfully) {
			throw new Exception("Объект "+table+" не загружен");
		}
    }

    @Override
    protected void update() throws SQLException {
        try (Statement st = con.createStatement()) {
			String q = "UPDATE "+table+" SET plan_id="+plan_id+", cow_group_id="+cow_group_id+
					", supplies_id = "+ supplies_id + ", quantity = "+ quantity + " " +
					"WHERE id="+id;
			st.executeUpdate(q);
		}
    }

    @Override
    protected void createNew() throws SQLException, Exception {
		try (Statement st = con.createStatement()) {
			String q = "INSERT INTO "+table+" (plan_id, cow_group_id, supplies_id, quantity) VALUES("+plan_id + "," + cow_group_id + ","
					+supplies_id+","+quantity+") ";
			st.executeUpdate(q);
			q="SELECT seq FROM sqlite_sequence WHERE name = '"+table+"'";
			ResultSet rs = st.executeQuery(q);
			if(rs.next()){
				id = rs.getInt("seq");
			}
			rs.close();
		}
    }
    
}
